import React, {PureComponent} from 'react';
import {connect, Provider} from 'react-redux';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  RefreshControl,
  DeviceEventEmitter,
  OverLayer,
  ActivityIndicator,
  TouchableOpacity,
  Platform,
  PermissionsAndroid,
  Image,
  Modal,
  Animated,
  Easing,
  PanResponder,
  Linking,
} from 'react-native';
import {SwipeListView} from 'react-native-swipe-list-view';
import {
  LinearButton,
  TextButton,
  LinearBoardButton,
  ImageButton,
} from '../../components/Button';
import I18n from 'react-native-i18n';
import {queryAllChannels, queryChannel} from '../../api/channel';
import {queryAuctionList} from '../../api/auction';
import {
  queryGamePurchase,
  updateGamePurchase,
  queryChannelPurchase,
  updateChannelPurchase,
} from '../../api';
import {shieldChannel, updateDeviceToken, bindWallet} from '../../api/user';
import {
  updateUserInfo,
  queryChainConfig,
  setCurrentRoom,
  setRoomWidgetLayout,
  setCurrentRoomSpeaker,
  setCurrentRoomListener,
  setCurrentRoomMuteUser,
  setRoomSpeakingUsers,
  setCurrentRoomRaisedUsers,
  setCurrentRoomOfflineUsers,
  clearRoomData,
  setCurrentRoomChatDatas,
  queryGameList,
  updateGameInfo,
} from '../../redux/action';
import {NormalHeader} from '../../components/NavigationHeader';
import RoomWidget from './components/RoomWidget';
import store from '../../redux/store';
import BaseComponent from '../base/BaseComponent';
import RtcEngine from 'react-native-agora';
import {formatMinuteTime, formatLeftTime} from '../../utils/tools';
import AuctionCell from './components/AuctionCell';
import {BASE_API, BASE_WSS} from '../../config';
import moment from 'moment';
import RoomCell from './components/RoomCell';
import ChainUtils from '../../utils/chain/ChainUtils';
import BigNumber from 'bignumber.js';
import JPushModule from 'jpush-react-native';
import ModalHandler from '../../components/ModalHandler';
import {LinerBoardTextInput} from '../../components/TextInput';
import RNFS from 'react-native-fs';
import StorageManager, {GAME_LIST, METAMASK_ADDRESS} from '../../storage';
import RNFetchBlob from 'rn-fetch-blob';
import {zip, unzip, unzipAssets, subscribe} from 'react-native-zip-archive';
import {Colors} from '../../styles/common';
import Browser from '../browser/index';
import GameIcon from '../../components/GameIcon';
import Device from '../../utils/device';
import EntryScriptWeb3 from '../../utils/EntryScriptWeb3';
import WalletConnectProvider from '@walletconnect/react-native-dapp';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {CachedImage} from 'react-native-img-cache';
import liveServer from '../../utils/LocalServer';
import SplashScreen from 'react-native-splash-screen';
import {resumableDownload} from '../../utils/download';
import {queryAppVersion} from '../../api/app';
import Iaphub from 'react-native-iaphub';
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#160231',
    padding: 0,
    position: 'relative',
  },
  selectBar: {
    backgroundColor: '#2B085E',
    marginLeft: 20,
    marginRight: 20,
    marginTop: 10,
    flexDirection: 'row',
    height: 50,
    borderRadius: 25,
    alignItems: 'center',
  },
  optionButton: {
    height: 35,
    flex: 1,
    marginLeft: 10,
    marginRight: 10,
    marginTop: 0,
  },
});

class HomeScreen extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      scollEnabled: false,
      isRefreshing: false,
      rooms: [],
      roomListPage: 1,
      roomListTotal: 0,
      roomListSize: 10,
      roomListIsLoadMore: false,
      widgetLoadingText: '',
      currentType: props.userInfo.disableGift ? 2 : 0,
      auctions: [],
      auctionListPage: 1,
      auctionListTotal: 0,
      auctionListSize: 10,
      auctionListIsLoadMore: false,
      didOpenRow: undefined,
      modalVisible: false,
      password: '',
      showProgressView: false,
      progress: 0,
      downloadText: 'Updating deesse resource',
      gameLayerOffset: Device.getDeviceHeight(),
      gameViewOffset: new Animated.Value(Device.getDeviceHeight()),
      loadGame: false,
      game: {},
      showSigninWebGame: false,
      signinOverlayerMarginBottom: 100,
      shouldHiddenGame: false,
      products: [],
    };

    // this.panResponder = PanResponder.create({
    //   onMoveShouldSetPanResponder: (evt, gestureState) => {
    //     //return true if user is swiping, return false if it's a single click
    //     return !(gestureState.dx === 0 && gestureState.dy === 0);
    //   },
    //   onPanResponderGrant: (evt, gestureState) => {},
    //   onPanResponderMove: (evt, gestureState) => {
    //     console.log(
    //       `gestureState.dx : ${gestureState.dx}   gestureState.dy : ${gestureState.dy}`,
    //     );
    //     this.setState({
    //       signinOverlayerMarginBottom:
    //         this.state.signinOverlayerMarginBottom - gestureState.dy,
    //     });
    //   },
    //   onPanResponderRelease: (evt, gestureState) => {
    //     console.log('marginBottom' + marginBottom);
    //     // StorageManager.save(WEB_MENU_BOTTOM, marginBottom + '');
    //   },
    //   onPanResponderTerminate: (evt, gestureState) => {},
    // });
  }

  componentDidMount() {
    super.componentDidMount();
    SplashScreen.hide();

    Iaphub.start({
      appId: '63b6383b32d8034e279d363c',
      apiKey: 'URLjfg0ulKrsAkWBKNrSIevd25oZqf4',
      allowAnonymousPurchase: true,
    })
      .then((res) => {
        console.log('did init iaphub');
        console.log(res);

        Iaphub.getProductsForSale()
          .then((res) => {
            console.log('products');
            console.log(res);
            this.setState({
              products: res,
            });
          })
          .catch((err) => {
            console.log('get products failed');
            console.log(err);
          });
      })
      .catch((err) => {
        console.log('init iaphub failed', err);
      });

    JPushModule.getRegistrationID((registObj) => {
      console.log('deviceToken' + JSON.stringify(registObj));
      // registerID
      // 设置别名
      if (
        registObj.registerID &&
        registObj.registerID.length != 0 &&
        this.props.userInfo.token
      ) {
        console.log('更新deviceToken');

        updateDeviceToken({
          userToken: this.props.userInfo.token,
          deviceToken: registObj.registerID,
        });

        JPushModule.setAlias({alias: registObj.registerID, sequence: 0}, () => {
          console.log('已设置别名');
          // console.log(alias);
        });
      }
    });

    //获取链的配置
    this.props.queryChainConfig(this.props.userInfo.token);

    queryAppVersion({
      app: Device.isIos() ? 'ios' : 'android',
    }).then((res) => {
      let {build, url, description, forceUpdate} = res.data;
      //
      console.log('服务器版本号为' + JSON.stringify(res));
      if (Device.existUpdateVersion(build)) {
        this._showAlert({
          content: 'New App Version\n\n' + description.replace(/\&/g, '\n'),
          okTitle: 'Update',
          alertOkPress: () => {
            Linking.openURL(url);
          },
          cancelTitle: !forceUpdate ? 'Cancel' : null,
        });
      }
    });

    //请求麦克风权限
    this.requestCameraAndAudioPermission();

    //判断是否有钱包，没钱包则跳转到创建钱包界面
    StorageManager.load(METAMASK_ADDRESS).then((res) => {
      console.log('本地存储的metamask地址' + res);
      if (res) {
        bindWallet({
          userToken: this.props.userInfo.token,
          address: JSON.parse(res).address,
        });
      }
    });

    //添加刷新的通知
    this.refreshChannelEmitter = DeviceEventEmitter.addListener(
      'refreshHomeList',
      this.onRefresh,
    );

    this.enterRoomEmitter = DeviceEventEmitter.addListener(
      'enterRoomEmitter',
      this.showRoomWidget,
    );

    this.micphoneEmitter = DeviceEventEmitter.addListener(
      'micphoneChange',
      this.micphoneChange,
    );

    this.voiceEmitter = DeviceEventEmitter.addListener(
      'voiceChange',
      this.voiceChange,
    );

    this.channelMessageEmitter = DeviceEventEmitter.addListener(
      'channelMessage',
      this.sendChannelMessage,
    );

    this.muteEmitter = DeviceEventEmitter.addListener(
      'muteUser',
      this.muteRemoteUser,
    );

    this.quitRoomEmitter = DeviceEventEmitter.addListener(
      'userQuitRoom',
      this.userQuitRoom,
    );

    this.webviewEvent = DeviceEventEmitter.addListener(
      'webview',
      this.handleWebEvent,
    );

    this.popRoomEmitter = DeviceEventEmitter.addListener(
      'popRoom',
      this.popRoom,
    );

    //开始获取数据
    this.onRefresh();

    EntryScriptWeb3.get();
  }

  async payForGame(index) {
    try {
      let products = [...this.state.products];
      if (products.length == 0) {
        products = await Iaphub.getProductsForSale();
        this.setState({
          products: products,
        });
      }

      let game = this.props.games[index];

      this._showLoading();

      var transaction = await Iaphub.buy(products[0].sku);
      console.log('Transaction successful: ', transaction);

      // {"currency": "HKD", "expirationDate": null, "group": null, "groupName": null, "id": "63b6600c32d8034e279d369c", "isFamilyShare": false, "isPromo": false, "isSubscriptionRenewable": false, "localizedDescription": "Paid Room", "localizedPrice": "HK$15", "localizedTitle": "Paid Room", "originalPurchase": null, "platform": "ios", "price": 15, "promoCode": null, "purchase": "63b6b45de5df7d14ade8b327", "purchaseDate": "2023-01-05T11:28:21.000Z", "sku": "sign_paid_room", "subscriptionDuration": null, "subscriptionIntroPhases": null, "subscriptionPeriodType": null, "subscriptionRenewalProduct": null, "subscriptionRenewalProductSku": null, "subscriptionState": null, "type": "consumable", "user": "63b6878ce5df7d14ade7ef51", "webhookStatus": "success"}
      setTimeout(async () => {
        await updateGamePurchase({
          userToken: this.props.userInfo.token,
          gameId: game.gameId,
          remark: JSON.stringify(transaction),
        });
        this._hideLoading();
        this.pressGame(index, false);
      }, 1000);
    } catch (err) {
      console.log(
        `Error: Transaction failed, message: ${err.message}, code: ${err.code}, subcode: ${err.subcode}`,
      );
      this._showAlert({
        content: err.message || err,
      });
    }
  }

  async payForChannel(item) {
    try {
      let products = [...this.state.products];
      if (products.length == 0) {
        products = await Iaphub.getProductsForSale();
        this.setState({
          products: products,
        });
      }

      this._showLoading();

      var transaction = await Iaphub.buy(products[0].sku);
      console.log('Transaction successful: ', transaction);

      // {"currency": "HKD", "expirationDate": null, "group": null, "groupName": null, "id": "63b6600c32d8034e279d369c", "isFamilyShare": false, "isPromo": false, "isSubscriptionRenewable": false, "localizedDescription": "Paid Room", "localizedPrice": "HK$15", "localizedTitle": "Paid Room", "originalPurchase": null, "platform": "ios", "price": 15, "promoCode": null, "purchase": "63b6b45de5df7d14ade8b327", "purchaseDate": "2023-01-05T11:28:21.000Z", "sku": "sign_paid_room", "subscriptionDuration": null, "subscriptionIntroPhases": null, "subscriptionPeriodType": null, "subscriptionRenewalProduct": null, "subscriptionRenewalProductSku": null, "subscriptionState": null, "type": "consumable", "user": "63b6878ce5df7d14ade7ef51", "webhookStatus": "success"}
      setTimeout(async () => {
        await updateChannelPurchase({
          userToken: this.props.userInfo.token,
          channelId: item.item.channelId,
          remark: JSON.stringify(transaction),
        });
        this._hideLoading();
        this._onPressItem(item);
      }, 500);
    } catch (err) {
      console.log(
        `Error: Transaction failed, message: ${err.message}, code: ${err.code}, subcode: ${err.subcode}`,
      );
      this._showAlert({
        content: err.message || err,
      });
    }
  }

  requestCameraAndAudioPermission = async () => {
    try {
      if (Platform.OS !== 'android') return;

      const granted = await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
      ]);
      if (
        granted['android.permission.RECORD_AUDIO'] ===
        PermissionsAndroid.RESULTS.GRANTED
      ) {
        console.log('You can use the micphore');
      } else {
        console.log('Permission denied');
      }
    } catch (err) {
      console.warn(err);
    }
  };

  componentWillUnmount() {
    super.componentWillUnmount();

    if (this.refreshChannelEmitter) {
      this.refreshChannelEmitter.remove();
    }

    if (this.enterRoomEmitter) {
      this.enterRoomEmitter.remove();
    }

    if (this.micphoneEmitter) {
      this.micphoneEmitter.remove();
    }

    if (this.voiceEmitter) {
      this.voiceEmitter.remove();
    }

    if (this.quitRoomEmitter) {
      this.quitRoomEmitter.remove();
    }

    if (this.muteEmitter) {
      this.muteEmitter.remove();
    }

    if (this.channelMessageEmitter) {
      this.channelMessageEmitter.remove();
    }

    if (this.webviewEvent) {
      this.webviewEvent.remove();
    }

    this.popRoomEmitter && this.popRoomEmitter.remove();
  }

  showGameWebView = ({url, icon}) => {
    if (this.signinWebOverLayer) {
      this.signinWebOverLayer.close();
    }

    if (this.state.loadGame == false) {
      console.log('加载新游戏' + url);

      this.setState(
        {
          game: {
            url,
            icon: icon ? icon : 'https://signin.art/resource/web.png',
            ratio: 1,
          },
          loadGame: true,
          gameLayerOffset: 0,
          showSigninWebGame: false,
        },
        () => {
          this.gameOverLayer.show();
          Animated.timing(this.state.gameViewOffset, {
            toValue: 0,
            duration: 300,
            useNativeDriver: false,
            // easing: Easing.linear,
          }).start();
        },
      );
    } else if (url == this.state.game.url) {
      console.log('加载当前游戏');
      DeviceEventEmitter.emit('enterGame');

      this.setState(
        {
          gameLayerOffset: 0,
          showSigninWebGame: false,
        },
        () => {
          Animated.timing(this.state.gameViewOffset, {
            toValue: 0,
            duration: 300,
            useNativeDriver: false,
            // easing: Easing.linear,
          }).start();
        },
      );
    } else {
      console.log('已存在游戏页面，加载新游戏' + url);

      console.log('需要重新加载');
      this.gameOverLayer.close();

      this.setState(
        {
          loadGame: false,
        },
        () => {
          this.setState(
            {
              game: {
                url,
                icon: icon ? icon : 'https://signin.art/resource/web.png',
                ratio: 1,
              },
              loadGame: true,
              gameLayerOffset: 0,
              showSigninWebGame: false,
            },
            () => {
              this.gameOverLayer.show();
              Animated.timing(this.state.gameViewOffset, {
                toValue: 0,
                duration: 300,
                useNativeDriver: false,
                // easing: Easing.linear,
              }).start();
            },
          );
        },
      );
    }

    if (icon) {
      Image.getSize(icon, (width, height) => {
        if (width !== 0 && height !== 0) {
          this.setState({
            game: {
              ...this.state.game,
              ratio: height / width,
            },
          });
        }
      });
    }

    //如果存在聊天控件，先隐藏 再出现
    if (this.props.widgetLayout.show) {
      this.overlayRightBottom.close();
      this.overlayRightBottom.show();
    }
  };

  handleWebEvent = ({type}) => {
    if (type == 'close') {
      Animated.timing(this.state.gameViewOffset, {
        toValue: Device.getDeviceHeight(),
        duration: 300,
        useNativeDriver: false,
      }).start();

      setTimeout(() => {
        this.gameOverLayer.close();

        setTimeout(() => {
          this.setState({
            loadGame: false,
            gameLayerOffset: Device.getDeviceHeight(),
          });
        }, 200);
      }, 300);
    } else if (type === 'minsize') {
      Animated.timing(this.state.gameViewOffset, {
        toValue: Device.getDeviceHeight(),
        duration: 300,
        useNativeDriver: false,
      }).start();

      setTimeout(() => {
        this.setState(
          {
            showSigninWebGame: true,
            gameLayerOffset: Device.getDeviceHeight(),
          },
          () => {
            console.log('展示缩小的游戏icon');
            console.log(this.state.game);
            //需求改动暂不展示
            // this.signinWebOverLayer.show();
          },
        );
      }, 300);
    }
  };

  popRoom = (quitRoom = false) => {
    if (this.state.shouldHiddenGame) {
      if (quitRoom) {
        console.log('退出房间后，修改约束');
        console.log('更新前widgetLayout', this.props.widgetLayout);
        this.props.setRoomWidgetLayout({
          show: false,
        });
        console.log('更新后widgetLayout', this.props.widgetLayout);
      } else {
        this.showGameWebView(this.state.game);
      }

      this.setState({
        shouldHiddenGame: false,
      });
    }
  };

  _backgroundStateEmitter = (nextAppState) => {
    console.log('Home切换前后台');

    if (nextAppState != null && nextAppState === 'active') {
      //如果是true ，表示从后台进入了前台 ，请求数据，刷新页面。或者做其他的逻辑
      // this.onRefresh();
    } else if (nextAppState != null && nextAppState === 'background') {
    }
  };

  dissolution = () => {
    this._hideLoading();
    this._showAlert({content: I18n.t('home.disbanded')});

    console.log('收到通知，房间解散');
    this.quitRoom(false);
  };

  voiceChange = (status) => {
    if (this._engine) {
      this._engine.muteAllRemoteAudioStreams(status);
    }
  };
  micphoneChange = (status) => {
    if (this._engine) {
      this._engine.enableLocalAudio(status);
    }
  };

  createWsConnection = () => {
    return new Promise((resolve, reject) => {
      let ws = new WebSocket(
        `${BASE_WSS}/joinChannel?userToken=${this.props.userInfo.token}&channelId=${this.props.currentRoom.channelId}&password=${this.state.password}`,
      );
      ws.onopen = () => {
        console.log('connection opened');

        //ping包
        if (this.interval) {
          console.log('结束重连');
          clearInterval(this.interval);
          this.interval = 0;

          this.setState({
            widgetLoadingText: '',
          });

          DeviceEventEmitter.emit('reconnectSuccess');
        }

        setTimeout(() => {
          console.log('发送心跳包');
          ws.send(
            JSON.stringify({
              type: 'heart',
              data: {},
            }),
          ); // send a message
        }, 10 * 1000);
      };
      /**
       * ws消息响应
       * {"type":"join","channel":{"channelId":16,"name":"BTC to the moon","owner":1,"userAmount":5,"speakerAmount":null,"updateTime":"2021-03-04T12:44:17.000Z"},"user":{"currentChannel":"16","userId":3,"address":null,"phone":"13162552028","followAmount":null,"fansAmount":1,"image":null,"identify":null,"nickName":"用户68893936","introduction":null,"updateTime":"2021-03-04T12:44:17.000Z"}}
       * {"type":"levae","channel":{"updateTime":"2021-03-09 10:15:25","channelId":22,"name":"Hhh","owner":2,"userAmount":4,"speakerAmount":0},"user":{"updateTime":"2021-03-09 10:15:25","currentChannel":null,"userId":3,"address":null,"phone":"13162552028","followAmount":0,"fansAmount":1,"image":"","identify":null,"nickName":"用户68893936","introduction":null,"isSpeaker":0}}
       * @param {*} msg
       */
      ws.onmessage = (event) => {
        try {
          console.log('收到socket响应');
          let res = JSON.parse(event.data);
          console.log(JSON.stringify(res, null, 2));
          if (res.type == 'join') {
            console.log('有用户加入');

            console.log(this.props.speakers);
            console.log(this.props.listeners);

            let newListener = {
              ...res.user,
              id: res.user.identify,
              followerNum: res.user.followAmount,
              followingNum: res.user.fansAmount,
              bio: res.user.introduction,
              name: res.user.nickName,
              avatar: BASE_API + res.user.image,
              address: res.user.address,
              isSpeaker: res.user.isSpeaker,
              userId: res.user.userId,
              isRoomOwner: res.user.userId == this.props.currentRoom.owner,
            };

            //判断离线用户列表中是否有该用户，有则删除
            this.props.setCurrentRoomOfflineUsers(
              this.props.offlineUser.filter(
                (item) => item.id != newListener.id,
              ),
            );

            if (newListener.isSpeaker) {
              this.props.setCurrentRoomSpeaker(
                this.props.speakers
                  .filter((item) => item.id != newListener.id)
                  .concat([newListener]),
              );
            } else {
              this.props.setCurrentRoomListener(
                this.props.listeners
                  .filter((item) => item.id != newListener.id)
                  .concat([newListener]),
              );
            }
          } else if (res.type == 'leave') {
            console.log('有用户离开');

            if (
              this.props.speakers.some((item) => item.id == res.user.identify)
            ) {
              this.props.setCurrentRoomSpeaker(
                this.props.speakers.filter((item) => {
                  return item.id != res.user.identify;
                }),
              );
            } else if (
              this.props.listeners.some((item) => item.id == res.user.identify)
            ) {
              this.props.setCurrentRoomListener(
                this.props.listeners.filter((item) => {
                  return item.id != res.user.identify;
                }),
              );
            }
          } else if (res.type == 'dissolution') {
            console.log('房间解散');

            this.dissolution();
            DeviceEventEmitter.emit('quitRoomPage');
            //其他操作
          } else if (res.type == 'changeMemberStatus') {
            console.log('用户上麦下麦');

            let user = {
              ...res.user,
              id: res.user.identify,
              followerNum: res.user.followAmount,
              followingNum: res.user.fansAmount,
              bio: res.user.introduction,
              name: res.user.nickName,
              address: res.user.address,
              avatar: BASE_API + res.user.image,
              isSpeaker: res.user.isSpeaker,
              userId: res.user.userId,
              isRoomOwner: res.user.userId == this.props.currentRoom.owner,
            };

            if (res.user.isSpeaker == 1) {
              let listeners = this.props.listeners.filter((item) => {
                return item.identify != res.user.identify;
              });

              //更新用户集
              this.props.setCurrentRoomSpeaker(
                this.props.speakers
                  .filter((item) => item.id != res.user.identify)
                  .concat([user]),
              );
              this.props.setCurrentRoomListener(listeners);
            } else {
              let speakers = this.props.speakers.filter((item) => {
                return item.identify != res.user.identify;
              });

              this.props.setCurrentRoomSpeaker(speakers);
              this.props.setCurrentRoomListener(
                this.props.listeners
                  .filter((item) => item.id != res.user.identify)
                  .concat([user]),
              );
            }
          } else if (res.type == 'outroom') {
            console.log('用户被强制踢出房间');
            this.quitRoom(true);
            DeviceEventEmitter.emit('quitRoomPage');
          } else if (res.type == 'closeMicrophone') {
            console.log('用户被房主下麦');
            let user = {
              id: res.user.identify,
              followerNum: res.user.followAmount,
              followingNum: res.user.fansAmount,
              bio: res.user.introduction,
              name: res.user.nickName,
              address: res.user.address,
              avatar: BASE_API + res.user.image,
              isSpeaker: 0,
              userId: res.user.userId,
            };

            this.props.updateUserInfo({
              ...this.props.userInfo,
              isSpeaker: 0,
            });

            if (this._engine) {
              this._engine.enableLocalAudio(false);
            }

            let speakers = this.props.speakers.filter((item) => {
              return item.id != res.user.identify;
            });

            this.props.setCurrentRoomSpeaker(speakers);
            this.props.setCurrentRoomListener(
              this.props.listeners
                .filter((item) => item.id != res.user.identify)
                .concat([user]),
            );
          } else if (res.type == 'offline') {
            console.log('有用户离线');

            let user = {
              id: res.user.identify,
              followerNum: res.user.followAmount,
              followingNum: res.user.fansAmount,
              bio: res.user.introduction,
              name: res.user.nickName,
              address: res.user.address,
              avatar: BASE_API + res.user.image,
              isSpeaker: 0,
              userId: res.user.userId,
            };

            this.props.setCurrentRoomOfflineUsers(
              this.props.offlineUser
                .filter((item) => item.id != user.id)
                .concat([user]),
            );
            console.log(this.props.offlineUser);
          } else if (res.type == 'joinChannel') {
            if (res.data.status) {
              //判断断开连接后，是否需要重连
              this.leaveChannel = false;
              //判断离线用户列表中是否有该用户，有则删除
              this.props.setCurrentRoomOfflineUsers(
                this.props.offlineUser.filter((item) => {
                  return item.id != this.props.userInfo.identify;
                }),
              );
              resolve();
            } else {
              reject(res.data.msg);
            }
          } else if (res.type == 'raisedHand') {
            //添加举手用户
            let newHandUsers = {
              id: res.user.identify,
              followerNum: res.user.followAmount,
              followingNum: res.user.fansAmount,
              bio: res.user.introduction,
              name: res.user.nickName,
              avatar: BASE_API + res.user.image,
              address: res.user.address,
              isSpeaker: res.user.isSpeaker,
              userId: res.user.userId,
            };

            console.log('用户' + newHandUsers.name + '举手申请发言');

            if (res.status) {
              this.props.setCurrentRoomRaisedUsers(
                this.props.raisedHandUsers
                  .filter((item) => item.id != newHandUsers.id)
                  .concat([newHandUsers]),
              );
            } else {
              this.props.setCurrentRoomRaisedUsers(
                this.props.raisedHandUsers.filter(
                  (item) => item.id != newHandUsers.id,
                ),
              );
            }
          } else if (res.type == 'agreeRaisedHand') {
            this.props.updateUserInfo({
              ...this.props.userInfo,
              isSpeaker: 1,
              micphoneState: res.microphone != undefined ? res.microphone : 1,
              raisedHand: false,
            });
            //开关麦克风
            if (res.microphone == undefined || res.microphone == 1) {
              DeviceEventEmitter.emit('micphoneChange', true);
            }
          } else if (res.type == 'newOwner') {
            //初始化举手状态
            this.props.setCurrentRoomRaisedUsers([]);

            if (this.props.userInfo.raisedHand) {
              this.props.updateUserInfo({
                ...this.props.userInfo,
                raisedHand: false,
              });
            }

            //有新房主
            DeviceEventEmitter.emit('newOwner', res.user);
          } else if (res.type == 'chat') {
            let newUser = {
              id: res.user.identify,
              followerNum: res.user.followAmount,
              followingNum: res.user.fansAmount,
              bio: res.user.introduction,
              name: res.user.nickName,
              avatar: BASE_API + res.user.image,
              address: res.user.address,
              isSpeaker: res.user.isSpeaker,
              userId: res.user.userId,
              isRoomOwner: res.user.userId == this.props.currentRoom.owner,
              content: res.data,
              msgId: res.id,
            };

            if (
              !this.props.chatDatas.some((item) => {
                return item.msgId == res.id;
              })
            ) {
              //显示新的聊天
              this.props.setCurrentRoomChatDatas(
                this.props.chatDatas.concat([newUser]),
              );
            }
          } else {
            console.log('心跳响应');

            setTimeout(() => {
              if (ws) {
                ws.send(
                  JSON.stringify({
                    type: 'heart',
                    data: {},
                  }),
                );
              }
            }, 10 * 1000);
          }
        } catch (err) {
          console.log('收到未知类型的消息' + err);
          // console.log(event.data);
        }
      };

      ws.onerror = (e) => {
        console.log('an error occurred' + e.message);
      };

      ws.onclose = (e) => {
        console.log('socket被关闭');

        if (this.leaveChannel) {
          console.log(
            'socket结束，用户未成功建立链接 或者 用户离开房间，不需要重连',
          );
          return;
        }

        // if (!this.leaveChannel) {
        //   this.createWsConnection();
        // }

        if (!this.interval) {
          console.log('socket从服务器断开，进行重连');
          this.reConnect();
        } else {
          console.log('重连失败，再次尝试');
        }
      };

      //记住频道号
      ws.channelId = this.props.currentRoom.channelId + '';

      this.ws = ws;
    });
  };

  reConnect = () => {
    DeviceEventEmitter.emit('reconnect');

    this.setState({
      widgetLoadingText: I18n.t('room.reconnect'),
    });

    //每5秒重连一次
    this.interval = setInterval(() => {
      console.log('尝试重连');
      if (!this.leaveChannel) {
        this.createWsConnection();
      }
    }, 5 * 1000);
  };

  // 通过 this.state 传入你的 App ID, 创建并初始化 RtcEngine 实例。
  initAgora = async () => {
    console.log('初始化agora模块');
    this._engine = await RtcEngine.create('1243204b0ddf43149415fcd2751442c9');
    // 启用音频模块。
    await this._engine.enableAudio();
    await this._engine.setEnableSpeakerphone(true);

    let channel = this.props.currentRoom;
    console.log('当前的channel信息');
    console.log(channel.token);
    console.log(channel.channelName);
    console.log(this.props.userInfo.userId);
    // 通过 this.state.token 和 this.state.channelName 获取传入的 Token 和频道名。
    // 本地用户的 ID。数据类型为整型，且频道内每个用户的 uid 必须是唯一的。若将 uid 设为 0，则 SDK 会自动分配一个 uid，并在 JoinChannelSuccess 回调中报告。
    await this._engine
      .joinChannel(
        channel.token,
        channel.channelName,
        '',
        this.props.userInfo.userId,
      )
      .then((res) => {
        // console.log('================');
        // console.log(res);
      })
      .catch((err) => {
        console.log('加入频道错误');
        console.log(err);
      });

    //启用说话者音量提示，开启本地人声检测功能
    this._engine.enableAudioVolumeIndication(1000, 3, true);

    // 注册 UserJoined 回调。
    // 远端用户成功加入频道时，会触发该回调，并返回该用户的 id。
    this._engine.addListener('UserJoined', (uid, elapsed) => {
      console.log('UserJoined', uid, elapsed);
    });

    // 注册 UserOffline 回调。
    // 远端用户离开频道时，会触发该回调，并返回该用户的 id。
    this._engine.addListener('UserOffline', (uid, reason) => {
      console.log('UserOffline', uid, reason);
    });

    // 注册 JoinChannelSuccess 回调。
    // 本地用户成功加入频道时，会触发该回调。
    this._engine.addListener('JoinChannelSuccess', (channel, uid, elapsed) => {
      console.log('JoinChannelSuccess', channel, uid, elapsed);
    });

    //本地音频状态改变
    this._engine.addListener('LocalAudioStateChanged', (state, error) => {
      console.log('LocalAudioStateChanged', state, error);
    });

    /**
      提示频道内谁正在说话、说话者音量及本地用户是否在说话的回调
      speakers: AudioVolumeInfo[]，每个说话者的用户 ID 和音量信息的数组。
      在本地用户的回调中，此数组中包含以下成员:
      uid = 0;
      volume 等于 totalVolume，报告本地用户混音后的音量;
      vad，报告本地用户人声状态。
      在远端用户的回调中，此数组中包含以下成员：

      uid，表示每位说话者的用户 ID；
      volume，表示各说话者混音后的音量；
      vad = 0，人声检测对远端用户无效。
      如果报告的 speakers 数组为空，则表示远端此时没有人说话。
     */
    this._engine.addListener(
      'AudioVolumeIndication',
      (speakers, totalVolume) => {
        // console.log('AudioVolumeIndication');
        // console.log(JSON.stringify(speakers, null, 2));
        // console.log(totalVolume);

        let arrs = [...this.props.speakingUsers];

        if (
          speakers.length == 1 &&
          speakers[0].channelId === '' &&
          speakers[0].uid == 0
        ) {
          if (arrs.some((item) => item.uid == this.props.userInfo.userId)) {
            arrs.map((item) => {
              if (item.uid == this.props.userInfo.userId) {
                item.volume = speakers[0].volume;
              }
            });
          } else {
            arrs.push({
              ...speakers[0],
              uid: this.props.userInfo.userId,
            });
          }
        } else {
          arrs = arrs.filter((item) => item.uid == this.props.userInfo.userId);
          arrs = arrs.concat(speakers);
        }
        this.props.setRoomSpeakingUsers(arrs);
      },
    );

    //如果进来是听众则关闭麦克风
    if (!this.props.userInfo.isSpeaker) {
      console.log('关闭麦克风');
      this._engine.enableLocalAudio(false);
    }
  };

  userQuitRoom = async (param) => {
    let needQuitRoomScreen =
      param && param.needQuitRoomScreen != undefined
        ? param.needQuitRoomScreen
        : true;

    let dissolution =
      param && param.dissolution != undefined ? param.dissolution : false;

    console.log('-------------');
    console.log(dissolution);
    this.quitRoom(false, dissolution);

    console.log('-----------------------');
    console.log(this.props.room);
    //检查是否需要进入游戏页面
    this.popRoom(true);

    if (needQuitRoomScreen) {
      DeviceEventEmitter.emit('quitRoomPage');

      this.onRefresh();
    }
  };

  sendChannelMessage = async (message) => {
    //发送ws消息
    console.log('发ws消息' + message);
    this.ws.send(JSON.stringify(message));
  };

  // 将远程用户静音
  muteRemoteUser = async (userId) => {
    let mute = this.props.muteUsers.some((item) => item == userId);

    if (mute) {
      let newMuteUsers = this.props.muteUsers.filter((item) => item != userId);
      this.props.setCurrentRoomMuteUser(newMuteUsers);
    } else {
      let newArr = [...this.props.muteUsers];
      newArr.push(userId);
      this.props.setCurrentRoomMuteUser(newArr);
    }
    this._engine.muteRemoteAudioStream(userId, !mute);
  };

  quitChannel = async (dissolution = false) => {
    this.leaveChannel = true;

    console.log('离开------');
    console.log(this.ws);
    //离开ws
    if (this.ws) {
      console.log('关闭socket链接，是否解散' + dissolution);
      if (dissolution) {
        this.ws.send(
          JSON.stringify({
            type: 'dissolution',
            data: {},
          }),
        );
      } else {
        this.ws.send(
          JSON.stringify({
            type: 'quit',
            data: {},
          }),
        );
      }
    }

    //离开频道
    if (this._engine) {
      await this._engine.leaveChannel();
    }

    //重置数据
    await this.props.updateUserInfo({
      ...this.props.userInfo,
      micphoneState: false,
      currentChannel: null,
    });

    //清除房间数据
    this.props.clearRoomData();

    console.log('清除后的数据');
    console.log(this.props.currentRoom);

    //结束重连
    if (this.interval) {
      console.log('结束重连');
      clearInterval(this.interval);
      this.interval = 0;
    }
  };

  quitRoom = (force = false, dissolution = false) => {
    console.log('关闭视图');

    try {
      this.showRoomWidget(false);

      if (force) {
        this._showAlert({content: 'You are forced to exit'});
      }
      console.log(222222222);
      this.quitChannel(dissolution);
    } catch (err) {
      console.log('退出错误');
    }
  };

  showRoomWidget = (isShow) => {
    try {
      if (this.overlayRightBottom) {
        if (isShow) {
          this.overlayRightBottom.show();
        } else {
          this.overlayRightBottom.close();
        }
      }

      console.log(this.props.widgetLayout.show);
      this.props.setRoomWidgetLayout({
        show: isShow,
      });
      console.log('关闭房间视图');
    } catch (err) {
      console.log('关闭房间视图失败');
    }
  };

  _initData = async () => {
    //更新用户信息
    if (!this.props.currentRoom) {
      await this.props.updateUserInfo();
    }

    let userToken = this.props.userInfo.token;

    console.log('用户token为' + userToken);

    if (this.state.currentType == 2) {
      await queryAllChannels({userToken})
        .then((res) => {
          console.log('查询房间信息为:');
          console.log(JSON.stringify(res.data.rows));
          //更新房间信息
          this.setState({
            rooms: res.data.rows,
            roomListTotal: res.data.pageInfo.total,
            roomListIsLoadMore: false,
          });
        })
        .catch((err) => {
          console.log('查询房间列表错误');
          console.log(err);
        });
    } else if (this.state.currentType == 1) {
      let {auctionListPage, auctionListSize} = this.state;
      await queryAuctionList({
        page: auctionListPage,
        size: auctionListSize,
      })
        .then((res) => {
          let newActions = res.data.rows.map((item) => {
            console.log(item.expireDate);

            let timeSpace =
              new Date(item.expireDate * 1000) - new Date().valueOf();

            let startPrice = new BigNumber(item.startPrice);
            const decimal = new BigNumber(Math.pow(10, item.payCoinDecimal));
            let vAmount = parseFloat(startPrice.dividedBy(decimal));

            startPrice = ChainUtils.subStringNum(vAmount, 4);

            let bidValue = new BigNumber(item.bidValue);
            let bAmount = parseFloat(bidValue.dividedBy(decimal));
            bidValue = ChainUtils.subStringNum(bAmount, 4);

            let dealPrice = new BigNumber(item.dealPrice);
            let dAmount = parseFloat(dealPrice.dividedBy(decimal));
            dealPrice = ChainUtils.subStringNum(dAmount, 4);

            return {
              ...item,
              img: item.img,
              leftTime: formatLeftTime(timeSpace),
              startPrice,
              bidValue,
              dealPrice,
            };
          });

          if (auctionListPage != 1) {
            newActions = this.state.auctions.concat(newActions);
          }

          this.setState({
            auctions: newActions,
            auctionListTotal: res.data.pageInfo.total,
            auctionListIsLoadMore: false,
          });
        })
        .catch((err) => {
          console.log('查询拍卖列表出错' + err);
        });
    } else {
      //查询支持的游戏
      this.props.queryGameList().then((res) => {
        console.log('^^^^^');
        console.log(this.props.games);
      });
    }
  };

  roomListOnRefresh = async () => {
    this.setState(
      {
        roomListPage: 1,
      },
      () => {
        this.onRefresh();
      },
    );
  };

  pressGame = async (index, resume = false) => {
    // if (!this.checkWalletConnect()) {
    //   return;
    // }
    let game = this.props.games[index];

    if (game.paid != 0) {
      let result = await queryGamePurchase({
        userToken: this.props.userInfo.token,
        gameId: game.gameId,
      });
      console.log('查询结果为');
      console.log(result);
      if (result.data.status == 0) {
        this._showAlert({
          content: `Your account has not purchased this game yet. Would you like to pay $${game.paid} for the game`,
          okTitle: 'Pay',
          alertOkPress: () => {
            console.log('pay it ');
            this.payForGame(index);
          },
          cancelTitle: 'Cancel',
        });

        return;
      }
    }

    console.log('当前游戏为' + JSON.stringify(game));

    //判断game是url类型还是本地类型
    if (game.path.indexOf('http') != -1) {
      this.showGameWebView({
        url: game.path,
        icon: game.icon,
      });
      return;
    }

    if (!resume && (this.task || game.progress !== undefined)) {
      this._showAlert({content: 'A game is downloading!'});
      return;
    }
    //母路径
    const path = RNFS.DocumentDirectoryPath + '/games';
    const gamePath = path + game.path;
    let gameUrlPaths = game.url.split('/');
    let resourcePath = path + '/' + gameUrlPaths[gameUrlPaths.length - 1];

    try {
      console.log('资源路径为' + path);

      let localGameInfos = await StorageManager.load(GAME_LIST);
      localGameInfos = localGameInfos ? JSON.parse(localGameInfos) : [];

      let localCurrentGame = localGameInfos.filter(
        (item) => item.name == game.name,
      );

      localCurrentGame =
        localCurrentGame.length == 0
          ? {
              name: game.name,
              version: '',
              unzipVersion: '',
            }
          : localCurrentGame[0];

      console.log('本地存储的游戏为：' + JSON.stringify(localCurrentGame));

      //校验文件是否下载并且解压完成
      let existsParentPath = await RNFS.exists(path);
      if (!existsParentPath) {
        console.log('创建deesse资源文件夹');
        await RNFS.mkdir(path);
        // await RNFS.mkdir(gamePath);
        StorageManager.save(GAME_LIST, null);
      } else {
        //校验子路径是否存在
        let existsGamePath = await RNFS.exists(gamePath);
        //重置本地游戏版本信息，处理本地游戏文件夹被外部应用删除的情况
        if (!existsGamePath) {
          localCurrentGame = {
            name: game.name,
            version: '',
            unzipVersion: '',
          };
          // await RNFS.mkdir(gamePath);
        }
      }

      console.log(localCurrentGame.version);
      console.log(game.version);

      //判断资源文件下载
      if (
        !localCurrentGame.version ||
        localCurrentGame.version != game.version
      ) {
        console.log('下载game zip 资源文件');
        console.log(game.url);

        if (
          localCurrentGame.version &&
          localCurrentGame.version != game.version
        ) {
          console.log('弹框提示用户');
          await this.alertGameUpdate();
          console.log('继续');
        }

        // this._showLoading('downloading deesse...');
        let existsGamePath = await RNFS.exists(gamePath);
        existsGamePath && (await RNFS.unlink(gamePath));

        if (game.progress == undefined) {
          this.props.updateGameInfo({
            ...game,
            progress: 0,
            showText: 'Loading...',
          });
        }

        let downloadFailed = false;
        await resumableDownload(
          path,
          game.url,
          (task) => {
            this.task = task;
          },
          (received, total) => {
            this.props.updateGameInfo({
              ...game,
              progress: received / total,
              showText: 'Loading...',
            });

            console.log(received);
            console.log(total);
            console.log('progress', received / total);
          },
        )
          .then((path) => {
            console.log('下载成功' + path);
            resourcePath = path;
          })
          .catch((err) => {
            console.log('下载资源失败', err);

            setTimeout(() => {
              this.pressGame(index, true);
            }, 5 * 1000);
            downloadFailed = true;
          });

        if (downloadFailed) {
          return;
        }

        localCurrentGame.version = game.version;

        StorageManager.save(
          GAME_LIST,
          JSON.stringify(
            localGameInfos
              .filter((item) => item.name != game.name)
              .concat([localCurrentGame]),
          ),
        );
      }

      //校验是否有解压完成标识
      if (
        !localCurrentGame.unzipVersion ||
        localCurrentGame.unzipVersion != game.version
      ) {
        this.props.updateGameInfo({
          ...game,
          progress: 1,
          showText: 'Unziping...',
        });

        let existsGamePath = await RNFS.exists(gamePath);
        existsGamePath && (await RNFS.unlink(gamePath));

        console.log('解压game zip资源文件', resourcePath);

        //解压deesse资源包
        await unzip(resourcePath, path).then((result) => {
          console.log('解压结果' + result);
        });

        //删除下载的包
        await RNFS.unlink(resourcePath);

        console.log(
          JSON.stringify(
            localGameInfos.filter((item) => item.name != game.name),
          ),
        );

        console.log(
          JSON.stringify(
            localGameInfos
              .filter((item) => item.name != game.name)
              .concat([localCurrentGame]),
          ),
        );

        localCurrentGame.unzipVersion = game.version;
        StorageManager.save(
          GAME_LIST,
          JSON.stringify(
            localGameInfos
              .filter((item) => item.name != game.name)
              .concat([localCurrentGame]),
          ),
        );
      }

      this.task = null;

      console.log('deesse资源加载成功，进入游戏');

      await liveServer.reStartServer();

      this.props.updateGameInfo({
        ...game,
        progress: undefined,
        showText: '',
      });

      this.showGameWebView({
        url: 'http://127.0.0.1:8080' + game.path,
        icon: game.icon,
      });
    } catch (err) {
      this.task = null;
      console.log('\n\n\n\n\n\n\n\ndeesse资源加载失败' + err);

      let existsGamePath = await RNFS.exists(resourcePath);
      existsGamePath && (await RNFS.unlink(resourcePath));

      this.props.updateGameInfo({
        ...game,
        progress: undefined,
        showText: '',
      });
      this._showAlert({
        content: 'failed to load deesse source' + err,
      });
    }
  };

  alertGameUpdate = async () => {
    return new Promise((resolve, reject) => {
      this._showAlert({
        content: 'New version found, please update',
        okTitle: 'Update',
        alertOkPress: () => {
          resolve();
        },
      });
    });
  };

  pressBrowser = async () => {
    this.props.navigation.navigate('BrowserGuide', {
      show: (url) => {
        this.showGameWebView({url});
      },
    });
  };

  cancelDownload = async () => {
    if (this.task) {
      await this.task.cancel((err) => {
        console.log('暂停出错' + err);
      });
      this.task = null;
    }
    this.setState({
      showProgressView: false,
      progress: 0,
    });
  };

  bgDownload = () => {
    this.setState({
      showProgressView: false,
    });
  };

  auctionListOnRefresh = async () => {
    this.setState(
      {
        auctionListPage: 1,
      },
      () => {
        this.onRefresh();
      },
    );
  };

  onRefresh = async () => {
    this.setState({
      isRefreshing: true,
    });
    //延时500ms
    await new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 100);
    });

    await this._initData();

    this.setState({
      isRefreshing: false,
    });

    // console.log(this.props.userInfo);

    if (
      this.props.userInfo.offline == 1 &&
      this.props.userInfo.currentChannel
    ) {
      console.log('用户掉线，加入频道');
      this._showLoading();
      try {
        queryChannel({
          userToken: this.props.userInfo.token,
          channelId: this.props.userInfo.currentChannel,
        })
          .then(async (res) => {
            if (
              !this.props.currentRoom ||
              this.props.currentRoom.channelId != res.data.channelId
            ) {
              //设置当前频道
              this.props.setCurrentRoom(res.data);

              //加入频道
              this.localJoinChannel()
                .then(async () => {
                  await this.props.updateUserInfo({
                    ...this.props.userInfo,
                    offline: 0,
                    offlineDate: null,
                    micphoneState: this.props.userInfo.isSpeaker ? 1 : 0,
                    isRoomOwner: this.props.userInfo.userId == res.data.owner,
                  });

                  console.log('用户自动加入掉线频道');

                  this._hideLoading();
                  this.props.navigation.navigate('Room', {
                    from: 'home',
                  });
                })
                .catch((err) => {
                  this._hideLoading();
                  //设置当前频道
                  this.props.setCurrentRoom(null);
                  this._showAlert({content: err + ''});
                });
            } else {
              this._hideLoading();
              this.props.navigation.navigate('Room', {
                from: 'home',
              });
            }
          })
          .catch((err) => {
            console.log(err);
            this.props.setCurrentRoom(null);

            this._hideLoading();
            this._showAlert({
              content: err,
              alertOkPress: () => {
                this.onRefresh();
              },
            });
          });
      } catch (err) {}
    }
  };

  _renderEmptyView = () => (
    <View
      style={{
        //   backgroundColor: 'yellow',
        width: '100%',
        height: 300,
        alignItems: 'center',
        justifyContent: 'center',
      }}>
      <Image
        style={{width: 95}}
        source={require('../../assets/browser/empty.png')}></Image>
      <Text style={{color: 'white', padding: 20, alignSelf: 'center'}}>
        {I18n.t('common.no_data')}
      </Text>
    </View>
  );
  _renderItemSeparatorComponent = () => (
    <View style={{height: 10, backgroundColor: 'transparent'}} />
  );

  _renderItem = (item) => (
    <RoomCell item={item} onPressItem={() => this._onPressItem(item)} />
  );

  _getQuickActions = (cell, rowMap) => {
    // console.log(cell);
    // console.log(rowMap);
    // console.log('重新获取元素');
    return (
      <View
        style={{
          flex: 1,
          flexDirection: 'row',
          justifyContent: 'flex-end',
          paddingRight: 20,
          paddingTop: 10,
          paddingBottom: 0,
        }}>
        <TouchableOpacity
          onPress={() => {
            // console.log(cell);
            // console.log(cell.item);

            //取消
            // console.log(this.state.didOpenRow);
            this.state.didOpenRow.closeRow();

            if (cell.item.owner == this.props.userInfo.userId) {
              this._showAlert({content: `You can't block your own room`});
            } else if (
              this.props.currentRoom &&
              this.props.currentRoom.channelId == cell.item.channel
            ) {
              this._showAlert({content: `Please exit the room`});
            } else {
              console.log('屏蔽房间，并刷新');
              shieldChannel({
                userToken: this.props.userInfo.token,
                channelId: cell.item.channelId,
              }).then((res) => {
                this.onRefresh();
              });
            }
          }}>
          <View
            style={{
              borderRadius: 20,
              backgroundColor: 'red',
              height: '100%',
              width: 120,
              justifyContent: 'center',
              alignItems: 'center',
            }}>
            <Text style={{color: 'white', fontSize: 16, marginLeft: 50}}>
              block
            </Text>
          </View>
        </TouchableOpacity>
      </View>
    );
  };

  _renderAuctionCellItem = (item) => (
    <AuctionCell
      auction={item.item}
      swapSymbol={this.props.swapSymbol}
      onPressItem={() => this._onPressAuction(item.item)}
    />
  );
  _onPressItem = async (item) => {
    console.log('current channel ', this.props.currentRoom);

    // this._showAlert({
    //   content: `Your account has not purchased this room yet. Would you like to pay $1 for the room`,
    //   okTitle: 'Pay',
    //   alertOkPress: () => {
    //     console.log('pay it ');
    //     this.payForGame(index);
    //   },
    //   cancelTitle: 'Cancel',
    // });
    // return;

    //直接进入当前房间
    if (
      this.props.currentRoom &&
      this.props.currentRoom.channelId == item.item.channelId
    ) {
      this.props.navigation.navigate('Room', {
        from: 'home',
      });
      return;
    }

    this._showLoading();
    if (
      this.props.currentRoom &&
      this.props.currentRoom.channelId != item.item.channelId
    ) {
      //先执行退出
      await this.quitChannel();
      this.showRoomWidget(false);
    }

    //查询房间是否存在
    queryChannel({
      userToken: this.props.userInfo.token,
      channelId: item.item.channelId,
    })
      .then(async (res) => {
        console.log('查询到的房间信息：' + JSON.stringify(res));
        //是否黑名单
        if (res.data.lastTime) {
          this._hideLoading();
          this._showAlert({
            content: I18n.t('home.noPermission').replace(
              '%s',
              formatMinuteTime(res.data.lastTime) + ' time',
            ),
          });
          return;
        }

        if (
          !this.props.currentRoom ||
          this.props.currentRoom.channelId != item.item.channelId
        ) {
          if (res.data.paid) {
            let result = await queryChannelPurchase({
              userToken: this.props.userInfo.token,
              channelId: res.data.channelId,
            });
            console.log('查询结果为');
            console.log(result);
            if (result.data.status == 0) {
              this._showAlert({
                content: `Your account has not purchased this chat room yet. Would you like to pay $1 for the room`,
                okTitle: 'Pay',
                alertOkPress: () => {
                  console.log('pay it ');
                  this.payForChannel(item);
                },
                cancelTitle: 'Cancel',
              });

              return;
            }
          }

          //设置当前频道
          this.props.setCurrentRoom(res.data);

          if (item.item.password) {
            this._hideLoading();
            this.setState({
              modalVisible: true,
            });
            return;
          }

          //加入频道
          this.localJoinChannel()
            .then(async () => {
              await this.props.updateUserInfo({
                ...this.props.userInfo,
                offline: 0,
                micphoneState: 0,
                isRoomOwner: this.props.userInfo.userId == res.data.owner,
                isSpeaker: res.data.owner == 99999,
              });

              this._hideLoading();
              this.props.navigation.navigate('Room', {
                from: 'home',
              });
            })
            .catch((err) => {
              this._hideLoading();
              //设置当前频道
              this.props.setCurrentRoom(null);
              this._showAlert({content: err + ''});
            });
        } else {
          this._hideLoading();
          this.props.navigation.navigate('Room', {
            from: 'home',
          });
        }
      })
      .catch((err) => {
        console.log(err);
        this.props.setCurrentRoom(null);
        this._hideLoading();
        this._showAlert({
          content: I18n.t('home.disbanded'),
          alertOkPress: () => {
            this.onRefresh();
          },
        });
      });
  };

  _onPressAuction = async (item) => {
    if (!this.checkWalletConnect()) {
      return;
    }

    console.log('点击拍卖详情');
    this.props.navigation.navigate('Auction', {auction: item});
  };

  createRoom = () => {
    // if (!this.checkWalletConnect()) {
    //   return;
    // }

    this.props.navigation.navigate('CreateRoom', {
      join: async () => {
        await this.localJoinChannel();
      },
    });
  };

  localJoinChannel = async () => {
    console.log('加入频道');

    return new Promise(async (resolve, reject) => {
      try {
        this.leaveChannel = true;
        //创建ws连接
        await this.createWsConnection();
        //初始化agora
        await this.initAgora();
        resolve();
      } catch (err) {
        console.log('==============');
        console.log(err);
        reject(err);
      }
    });
  };

  confirm = async () => {
    this.setState({
      modalVisible: false,
    });

    //加入频道
    this.localJoinChannel()
      .then(async (res) => {
        await this.props.updateUserInfo({
          ...this.props.userInfo,
          offline: 0,
          micphoneState: this.props.userInfo.isSpeaker ? 1 : 0,
        });
        this.props.navigation.navigate('Room', {
          from: 'home',
        });
      })
      .catch((err) => {
        // //设置当前频道
        this.props.setCurrentRoom(null);
        this._showAlert({content: err + ''});
      });
  };

  onPressBackground = () => {
    this.setState({
      modalVisible: false,
    });

    //设置当前频道
    this.props.setCurrentRoom(null);
  };

  auctionListFooterComponent = () => {
    // console.log(this.state);
    // console.log(this.state.auctions.length);
    let showLoadingMore =
      this.state.auctionListTotal >=
      this.state.auctionListPage * this.state.auctionListSize;
    return this.state.auctions.length == 0 ? null : (
      <View>
        <View
          style={{
            flexDirection: 'row',
            color: 'white',
            justifyContent: 'center',
          }}>
          {showLoadingMore ? (
            <ActivityIndicator size="small" animating={true} />
          ) : null}
          <Text style={{color: 'white', marginLeft: 10}}>
            {showLoadingMore ? 'loading more...' : ''}
          </Text>
        </View>
      </View>
    );
  };

  onAuctionFlatlistEndReached() {
    console.log('>>上拉加载>>>');
    const {
      auctionListPage,
      auctionListIsLoadMore,
      auctionListTotal,
      auctions,
    } = this.state;

    if (auctions.length < auctionListTotal && !auctionListIsLoadMore) {
      this.setState(
        {
          auctionListPage: auctionListPage + 1,
          auctionListIsLoadMore: true,
        },
        () => {
          this._initData();
        },
      );
    }
  }

  roomListFooterComponent = () => {
    let showLoadingMore =
      this.state.roomListTotal >=
      this.state.roomListPage * this.state.roomListSize;
    return this.state.rooms.length == 0 ? null : (
      <View>
        <View
          style={{
            flexDirection: 'row',
            color: 'white',
            justifyContent: 'center',
          }}>
          {showLoadingMore ? (
            <ActivityIndicator size="small" animating={true} />
          ) : null}
          <Text style={{color: 'white', marginLeft: 10}}>
            {showLoadingMore ? 'loading more...' : ''}
          </Text>
        </View>
      </View>
    );
  };

  onRoomFlatlistEndReached() {
    console.log('>>上拉加载>>>');
    const {roomListPage, roomListIsLoadMore, roomListTotal, rooms} = this.state;

    if (rooms.length < roomListTotal && !roomListIsLoadMore) {
      this.setState(
        {
          roomListPage: roomListPage + 1,
          roomListIsLoadMore: true,
        },
        () => {
          this._initData();
        },
      );
    }
  }

  _handlerView = () => {
    return (
      <View style={{width: '100%'}}>
        <Text
          style={{
            fontWeight: 'bold',
            marginTop: 20,
            marginBottom: 20,
            color: '#6701F4',
          }}>
          Room Password
        </Text>
        <LinerBoardTextInput
          style={{
            width: '100%',
            padding: 0,
            height: 44,
          }}
          secureTextEntry={true}
          onChangeText={(text) => {
            this.setState({
              password: text,
            });
          }}
          placeholder="input room password"></LinerBoardTextInput>
        <View
          style={{
            width: '100%',
            flexDirection: 'row',
            justifyContent: 'flex-end',
            marginBottom: 30,
          }}>
          <LinearBoardButton
            buttonStyle={{
              width: 100,
              height: 30,
              marginRight: 20,
            }}
            onPress={() => {
              this.props.setCurrentRoom(null);
              this.setState({
                modalVisible: false,
              });
            }}
            text={'Cancel'}></LinearBoardButton>
          <LinearButton
            buttonStyle={{
              width: 100,
              height: 30,
            }}
            onPress={this.confirm}
            text={'Confirm'}></LinearButton>
        </View>
      </View>
    );
  };

  renderComponent = () => {
    let {currentType, modalVisible} = this.state;
    let {games} = this.props;

    // console.log('games' + JSON.stringify(games));
    let _this = this;
    let rightMenu = [
      {
        onPress: () => {
          this.props.navigation.navigate('Message');
        },
        icon:
          this.props.userInfo.unreadMessageAmount == 0
            ? require('../../assets/home/alert.png')
            : require('../../assets/home/alert_unread.png'),
      },
      {
        containerStyle: {
          paddingLeft: 4,
          paddingRight: 4,
          paddingTop: 4,
          paddingRight: 4,
        },
        mode: 'cover',
        onPress: () => {
          this.props.navigation.navigate('UserInfo', {
            showLogout: true,
            quit: () => {
              if (this.props.currentRoom) {
                console.log('退出房间');
                _this.quitRoom();
              } else {
                console.log('不需要退出房间');
              }
            },
          });
        },
        imageStyle: {borderRadius: 30, width: 32, height: 32},
        icon: {
          uri: this.props.userInfo.image,
        },
      },
    ];

    //抽奖功能暂时注释
    // if (!this.props.userInfo.disableGift) {
    //   rightMenu.unshift({
    //     onPress: () => {
    //       this.props.navigation.push('AwardCenter');
    //     },
    //     icon: require('../../assets/home/lottery_icon.png'),
    //   });
    // }

    return (
      <View style={styles.container}>
        <NormalHeader
          navigation={this.props.navigation}
          left={{
            icon: require('../../assets/home/search.png'),
            onPress: () => {
              this.props.navigation.navigate('Search');
            },
          }}
          right={rightMenu}
        />
        {!this.props.userInfo.disableGift ? (
          <View style={styles.selectBar}>
            {currentType == 0 ? (
              <LinearButton
                text={'Game'}
                buttonStyle={[styles.optionButton, {marginLeft: 10}]}
                textStyle={{color: 'white'}}
                onPress={() => {
                  this.setState({currentType: 0});
                }}
              />
            ) : (
              <TextButton
                text={'Game'}
                textStyle={{color: 'white'}}
                buttonStyle={[
                  styles.optionButton,
                  {backgroundColor: 'transport', marginLeft: 10},
                ]}
                onPress={() => {
                  this.setState({currentType: 0}, () => {
                    this.onRefresh();
                  });
                }}
              />
            )}
            {currentType == 1 ? (
              <LinearButton
                text={'Auction'}
                buttonStyle={[styles.optionButton, {marginLeft: 0}]}
                textStyle={{color: 'white'}}
                onPress={() => {
                  this.setState({currentType: 1}, () => {
                    if (this.state.auctions.length == 0) {
                      this.onRefresh();
                    }
                  });
                }}
              />
            ) : (
              <TextButton
                text={'Auction'}
                textStyle={{color: 'white'}}
                buttonStyle={[
                  styles.optionButton,
                  {backgroundColor: 'transport', marginLeft: 0},
                ]}
                onPress={() => {
                  this.setState({currentType: 1}, () => {
                    if (this.state.auctions.length == 0) {
                      this.onRefresh();
                    }
                  });
                }}
              />
            )}

            {currentType == 2 ? (
              <LinearButton
                text={'Chat'}
                buttonStyle={styles.optionButton}
                textStyle={{color: 'white'}}
                onPress={() => {
                  this.setState({currentType: 2}, () => {
                    if (this.state.rooms.length == 0) {
                      this.onRefresh();
                    }
                  });
                }}
              />
            ) : (
              <TextButton
                text={'Chat'}
                textStyle={{color: 'white'}}
                buttonStyle={[
                  styles.optionButton,
                  {backgroundColor: 'transport'},
                ]}
                onPress={() => {
                  this.setState({currentType: 2}, () => {
                    if (this.state.rooms.length == 0) {
                      this.onRefresh();
                    }
                  });
                }}
              />
            )}
          </View>
        ) : null}
        {/* 房间列表 */}
        {currentType == 2 ? (
          <View
            style={{
              flex: 1,
              padding: 0,
              position: 'relative',
            }}>
            <View style={{padding: 20}}>
              <View
                style={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}>
                <Text style={{color: 'white', fontSize: 12}}>
                  <Text style={{fontWeight: 'bold'}}>
                    {I18n.t('home.find_more1')}
                  </Text>
                  <Text>{I18n.t('home.find_more2')}</Text>
                </Text>
                <LinearButton
                  textStyle={{
                    fontSize: 14,
                    fontWeight: 'normal',
                    color: 'white',
                  }}
                  buttonStyle={{
                    height: 30,
                    paddingLeft: 10,
                    paddingRight: 10,
                    borderRadius: 15,
                    marginTop: 0,
                  }}
                  text="Find more"
                  onPress={() => {
                    this.props.navigation.navigate('Search');
                  }}></LinearButton>
              </View>
            </View>
            <SwipeListView
              useFlatList
              style={{marginBottom: 100}}
              data={this.state.rooms}
              keyExtractor={(item, index) => 'room' + item.channelId} // 给定的item生成一个不重复的key
              renderItem={this._renderItem}
              ListEmptyComponent={this._renderEmptyView}
              ItemSeparatorComponent={this._renderItemSeparatorComponent}
              ListFooterComponent={this.roomListFooterComponent}
              onEndReached={() => this.onRoomFlatlistEndReached()}
              onEndReachedThreshold={0.2}
              contentContainerStyle={{flexGrow: 1}}
              ListFooterComponentStyle={{flex: 1, justifyContent: 'flex-end'}}
              refreshControl={
                <RefreshControl
                  tintColor="white"
                  refreshing={this.state.isRefreshing}
                  onRefresh={this.roomListOnRefresh}
                  colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
                  progressBackgroundColor="#ffffff"
                />
              }
              renderHiddenItem={this._getQuickActions}
              closeOnRowPress={true}
              closeOnRowBeginSwipe={true}
              closeOnScroll={true}
              rightOpenValue={-75} //列表项右滑translateX的值：负值
              stopRightSwipe={-100} //列表项右滑translateX最大的值：负值
              disableRightSwipe={true} //禁止右滑
              onRowOpen={(rowKey, rowMap) => {
                //当滑动行的动画处于开启状态时调用
                // if (rowMap[1] !== undefined) {
                //   setTimeout(() => {
                //     rowMap[rowKey].closeRow();
                //   }, 2000);
                // }

                // console.log(rowKey);
                // console.log(rowMap);

                this.setState({
                  didOpenRow: rowMap[rowKey],
                });
              }}
            />
            {/* 当没加入房间时显示创建房间按钮 */}
            {this.props.currentRoom ? null : (
              <View
                style={{
                  position: 'absolute',
                  bottom: 30,
                  width: '100%',
                  flexDirection: 'row',
                  justifyContent: 'center',
                  zIndex: 1000,
                }}>
                <LinearButton
                  text={
                    this.props.userInfo.disableGift
                      ? 'Create Room'
                      : 'Chat to earn'
                  }
                  buttonStyle={{paddingLeft: 20, paddingRight: 20}}
                  onPress={this.createRoom}></LinearButton>
              </View>
            )}
          </View>
        ) : null}
        {/* 拍卖 */}
        {currentType == 1 ? (
          <View
            style={{
              flex: 1,
              padding: 0,
              position: 'relative',
            }}>
            <FlatList
              style={{marginBottom: 100, flex: 1, marginTop: 10}}
              data={this.state.auctions}
              keyExtractor={(item, index) => item.auctionId} // 给定的item生成一个不重复的key
              renderItem={this._renderAuctionCellItem}
              ListEmptyComponent={this._renderEmptyView}
              ItemSeparatorComponent={this._renderItemSeparatorComponent}
              ListFooterComponent={this.auctionListFooterComponent}
              onEndReached={() => this.onAuctionFlatlistEndReached()}
              onEndReachedThreshold={0.2}
              contentContainerStyle={{flexGrow: 1}}
              ListFooterComponentStyle={{flex: 1, justifyContent: 'flex-end'}}
              refreshControl={
                <RefreshControl
                  tintColor="white"
                  refreshing={this.state.isRefreshing}
                  onRefresh={this.auctionListOnRefresh}
                  colors={['#ff0000', '#00ff00', '#0000ff', '#3ad564']}
                  progressBackgroundColor="#ffffff"
                />
              }
            />
            <View
              style={{
                position: 'absolute',
                bottom: 30,
                width: '100%',
                flexDirection: 'row',
                justifyContent: 'center',
                zIndex: 1000,
              }}>
              <LinearButton
                text="Start an auction"
                buttonStyle={{paddingLeft: 20, paddingRight: 20}}
                onPress={() => {
                  if (!this.checkWalletConnect()) {
                    return;
                  }

                  this.props.navigation.navigate('SelectNTF');
                }}
              />
            </View>
          </View>
        ) : null}
        {/* 游戏 */}
        {currentType == 0 ? (
          <View
            style={{
              flex: 1,
              padding: 0,
              position: 'relative',
              flexDirection: 'row',
              padding: 20,
              flexWrap: 'wrap',
              paddingTop: 0,
            }}>
            {games.map((item, index) => {
              return (
                <GameIcon
                  key={item.name}
                  containerStyle={{
                    marginRight: (index + 1) % 3 == 0 ? 0 : 20,
                    marginTop: 20,
                  }}
                  progress={{
                    show: true,
                    value: item.progress,
                  }}
                  name={item.progress !== undefined ? item.showText : item.name}
                  onPress={() => {
                    this.pressGame(index);
                  }}
                  icon={item.icon}></GameIcon>
              );
            })}
            <GameIcon
              containerStyle={{
                marginRight: (games.length + 1) % 3 == 0 ? 0 : 20,
                marginTop: 20,
              }}
              addMode={true}
              onPress={this.pressBrowser}
              icon={require('../../assets/game/game_add.png')}></GameIcon>
          </View>
        ) : null}
        <ModalHandler
          visible={modalVisible}
          handlerView={this._handlerView}
          onPressBackground={this.onPressBackground}
        />
        <OverLayer
          ref={(ele) => {
            this.overlayRightBottom = ele;
          }}
          style={{
            bottom: this.props.widgetLayout.bottom,
            height: this.props.widgetLayout.height,
            width: '100%',
            backgroundColor: 'transparent',
          }}>
          <View style={{position: 'absolute', bottom: 0, width: '100%'}}>
            <Provider store={store}>
              <RoomWidget
                ref={(ele) => {
                  this.room = ele;
                }}
                loadingText={this.state.widgetLoadingText}
                back={() => {
                  console.log('退出聊天室事件');
                  _this.quitRoom();
                  DeviceEventEmitter.emit('quitRoomPage');
                }}
                pressUserIcon={async () => {
                  //判断如果当前出现了游戏视图，则需要先收起游戏视图
                  if (this.state.gameLayerOffset == 0) {
                    console.log('缩小游戏视图');

                    DeviceEventEmitter.emit('notifyMiniSizeGame', false);

                    this.setState({
                      gameViewOffset: new Animated.Value(
                        Device.getDeviceHeight(),
                      ),
                      showSigninWebGame: true,
                      gameLayerOffset: Device.getDeviceHeight(),
                      shouldHiddenGame: true,
                    });
                  } else {
                    console.log('当前未加载游戏，不需要加载游戏视图');
                  }

                  DeviceEventEmitter.emit('enterRoom');
                }}
              />
            </Provider>
          </View>
        </OverLayer>
        <OverLayer
          ref={(ele) => {
            this.gameOverLayer = ele;
          }}
          style={{
            height: this.props.widgetLayout.show
              ? Device.getDeviceHeight() - 100
              : '100%',
            width: '100%',
            position: 'relative',
            marginTop: this.state.gameLayerOffset,
          }}>
          {this.state.loadGame ? (
            <Animated.View
              style={{
                // position: 'absolute',
                width: '100%',
                height: '100%',
                // left: 0,
                marginTop: this.state.gameViewOffset,
              }}>
              <WalletConnectProvider
                redirectUrl={
                  Platform.OS === 'web'
                    ? window.location.origin
                    : `siginclub://`
                }
                storageOptions={{
                  asyncStorage: AsyncStorage,
                }}>
                <Provider store={store}>
                  <Browser url={this.state.game.url} />
                </Provider>
              </WalletConnectProvider>
            </Animated.View>
          ) : null}
        </OverLayer>
        {this.state.showSigninWebGame ? (
          <OverLayer
            ref={(ele) => {
              this.signinWebOverLayer = ele;
            }}
            style={{
              width: 40,
              height: 40,
              backgroundColor: 'rgba(255,255,255,0.85)',
              borderTopRightRadius: 20,
              borderBottomRightRadius: 20,
              position: 'absolute',
              left: 3,
              bottom: this.state.signinOverlayerMarginBottom,
            }}>
            <TouchableOpacity
              style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}
              onPress={() => {
                this.showGameWebView(this.state.game);
              }}>
              <View
                style={{
                  width: 30,
                  height: 30,
                  borderRadius: 15,
                  backgroundColor: '#000',
                  overflow: 'hidden',
                  justifyContent: 'center',
                  alignItems: 'center',
                }}>
                <CachedImage
                  style={{
                    width: 24,
                    height:
                      24 * (this.state.game.ratio ? this.state.game.ratio : 1),
                  }}
                  source={{uri: this.state.game.icon}}></CachedImage>
              </View>
            </TouchableOpacity>
          </OverLayer>
        ) : null}
      </View>
    );
  };
}

const mapStateToProps = (state) => ({
  userInfo: state.User.userInfo,
  currentRoom: state.User.currentRoom,
  widgetLayout: state.Layout.widgetLayout,
  speakers: state.User.speakers,
  listeners: state.User.listeners,
  currentRouter: state.Layout.currentRouter,
  offlineUser: state.User.offlineUser,
  gasSymbol: state.Chain.gasSymbol,
  swapSymbol: state.Chain.swapSymbol,
  muteUsers: state.User.muteUsers,
  speakingUsers: state.User.speakingUsers,
  raisedHandUsers: state.User.raisedHandUsers,
  chatDatas: state.User.chatDatas,
  games: state.Game.games,
});

const mapDispatchToProps = (dispatch) => ({
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
  queryChainConfig: (item) => dispatch(queryChainConfig(item)),
  setCurrentRoom: (item) => dispatch(setCurrentRoom(item)),
  setCurrentRoomListener: (item) => dispatch(setCurrentRoomListener(item)),
  setCurrentRoomSpeaker: (item) => dispatch(setCurrentRoomSpeaker(item)),
  setRoomWidgetLayout: (item) => dispatch(setRoomWidgetLayout(item)),
  setCurrentRoomMuteUser: (item) => dispatch(setCurrentRoomMuteUser(item)),
  setRoomSpeakingUsers: (item) => dispatch(setRoomSpeakingUsers(item)),
  setCurrentRoomRaisedUsers: (item) =>
    dispatch(setCurrentRoomRaisedUsers(item)),
  setCurrentRoomOfflineUsers: (item) =>
    dispatch(setCurrentRoomOfflineUsers(item)),
  clearRoomData: () => dispatch(clearRoomData()),
  setCurrentRoomChatDatas: (item) => dispatch(setCurrentRoomChatDatas(item)),
  queryGameList: (item) => dispatch(queryGameList(item)),
  updateGameInfo: (item) => dispatch(updateGameInfo(item)),
});

export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen);
